package com.avalon.core.select;

import com.avalon.core.field.Field;
import com.avalon.core.field.FieldList;
import com.avalon.core.field.SelectionField;
import com.avalon.core.select.builder.SelectBuilder;
import com.avalon.core.service.AbstractService;
import com.avalon.core.util.FieldUtils;

public class OrderField {
    private String originField;
    private Field field;//最后一个字段
    private FieldList tableList;
    private String order;//排序方式
    private AbstractService service;

    public FieldList getTableList() {
        return tableList;
    }

    protected void setTableList(FieldList tableList) {
        this.tableList = tableList;
    }

    public String getOriginField() {
        return originField;
    }

    protected void setOriginField(String originField) {
        this.originField = originField;
    }

    public Field getField() {
        return field;
    }

    protected void setField(Field field) {
        this.field = field;
    }

    public OrderField(String originField, String order, AbstractService service) {
        this.originField = originField;
        this.field = service.getField(originField);
        this.order = order;
        this.service = service;
    }

    public StringBuilder getOrderSql(SelectBuilder builder) {
        StringBuilder sql = new StringBuilder();
        String orderAlias = builder.getOrderAlias(originField);
        if (field instanceof SelectionField) {
            String[] fieldOrder = ((SelectionField) field).getFieldOrder();

            if (fieldOrder.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (String field : fieldOrder) {
                    sb.append(",").append("'").append(field).append("'");
                }
                sql.append("FIELD(");
                sql.append(orderAlias).append(FieldUtils.getJoinDivision()).append(field.getFieldName());
                sql.append(sb);
                sql.append(")");
            } else {
                sql.append(orderAlias).append(FieldUtils.getJoinDivision()).append(field.getFieldName());
                sql.append(" ").append(order);
            }

        } else {
            sql.append(orderAlias).append(FieldUtils.getJoinDivision()).append(field.getFieldName());
            sql.append(" ").append(order);
        }

        return sql;
    }
}
